package com.zr.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.zr.dao.BaseDao;
import com.zr.dao.FunctionDao;
import com.zr.model.Func;
import com.zr.model.Role;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Repository("functionDao")
public class FunctionDaoImpl<T> extends  BaseDaOImpl<T> implements FunctionDao{
		
	@Resource
	private BaseDao<Func>  baseDao;
	
	
	@Override
	public JSONArray findUserFunctionByRole(String funcs, int parentId) {
		String hql = "select * from Func func where func.fid in ("+funcs+") and pid=:pid";
		JSONArray rolefuncs = new JSONArray();
		Query  query  =  this.getCurrentSession().createSQLQuery(hql).addEntity(Func.class);
		query.setInteger("pid",parentId);
		List<Func>  fs = query.list();
		for (Func Func : fs) {
			JSONObject j = new JSONObject();
			j.put("id", Func.getFid());
			j.put("text",Func.getFname());
			j.put("state",Func.getFstate());
			JSONObject attr = new JSONObject();
			attr.put("furl", Func.getFurl());
			j.put("attributes", attr);
			rolefuncs.add(j);		
		}
		return rolefuncs;
	}
	
	public JSONArray findUserAllFunctionByRole(String funcs, int parentId){
		List<Func> list  = this.findUserFunctionByRole(funcs, parentId);
		JSONArray userfuncs = JSONArray.fromObject(list);
		for (int i = 0; i < userfuncs.size(); i++) {
			  String state = userfuncs.getJSONObject(i).getString("state");
			  if("open".equals(state)){
				     continue;
			  }else{
				   int currentId = userfuncs.getJSONObject(i).getInt("id");
				   JSONArray   children  = JSONArray.fromObject(this.findUserAllFunctionByRole(funcs, currentId));
				   userfuncs.getJSONObject(i).put("children", children);
			  }
		}
		return userfuncs;
	}

}
